#ifndef BLOCK_H
#define BLOCK_H

#include <vector>

enum Content{AD=0, MOVIE=2, UNDEFINED=1};

class Block
{
	public:

		Content getContent()
		{
			return content;
		}

		int getStartFrame()
		{
			return startFrame;
		}

		int getEndFrame()
		{
			return endFrame;
		}

		bool inBlock(int frameNo)
		{
			bool inBlock = false;

			// startFrame is inclusive endFrame is exclusive
			if(frameNo >= startFrame && frameNo < endFrame)
			{
				inBlock = true;
			}

			return inBlock;
        }

		Block(int start, int end, Content type)
		{
			if(start < end)
			{
				startFrame = start;
				endFrame = end;
				content = type;
            }
        }

	private:
		int startFrame;
		int endFrame;
		Content content;
};

class Blocklist
{
	public:
		bool insertBlock(Block block)
		{
			bool successful = false;
			// first block?
			if(blockVector.empty())
			{
				blockVector.push_back(block);
				successful = true;
			}
			else
			{
				// rightmost element?
				if(blockVector.back().getEndFrame() <= block.getStartFrame())
				{
                 	blockVector.push_back(block);
					successful = true;
				}
				else   // block not the rightmost
				{
					// iterate reverse because normally the blocks are
					// already ordered
					std::vector<Block>::reverse_iterator rit;
					for ( rit=blockVector.rbegin() ; rit < blockVector.rend();
						 ++rit
					)
					{
						if(rit->getEndFrame() <= block.getStartFrame()
							&& block.getEndFrame() <= (rit + 1)->getStartFrame()
						)
						{
							blockVector.insert(rit.base() + 1, block);
							successful = true;
							break;
                        }
					}
				}


            }

			return successful;
		}

		int getNumberOfBlocks()
		{
            return (int)blockVector.size();
		}

		Content getFrameContent(int frameNo)
		{
			std::vector<Block>::iterator it;
			Content content = UNDEFINED;

			for ( it=blockVector.begin() ; it < blockVector.end(); it++ )
			{
				if(it->getStartFrame() <= frameNo && it->getEndFrame() > frameNo)
				{
					content = it->getContent();
					break;
                }
			}

			return content;
		}

		int getMovieLength()
		{
            return blockVector.back().getEndFrame();
		}

		void clear()
		{
            blockVector.clear();
        }

		Block getBlock(int number)
		{
            return blockVector[number];
        }

	private:
		std::vector<Block> blockVector;
};

#endif /* BLOCK_H */
